import GeneralConfig from '../config/general-config';
import LocalStorageService from './local-storage-service';

/**
 * The service provides method against authentication.
 *
 * Current active user info is saved in local storage with key [GeneralConfig.localUserInfoStorageKey].
 * This is used to determine if user is logged in or not.
 *
 * The active user access token is saved in local storage with key [GeneralConfig.localAccessTokenStorageKey].
 *
 * IMPORTANT!!!
 * Never ever saves user plain password on client side!!!
 */
export default class AuthenticationService {
  // Loads the user from session storage at the first time.
  static currentUser = LocalStorageService.loadLocalData(GeneralConfig.localUserInfoStorageKey);

  // Sets authentication status based on local user info.
  static isAuthenticated: boolean = AuthenticationService.currentUser != null;

  // Stores the URL so we can redirect after logging in
  // let redirectUrl: string | undefined | null;

  /**
   * Notifies the observer that user has logged out.
   * @param user The user object that will be sent to all observers.
   */
  static saveUserInfo(user: any): void {
    LocalStorageService.saveLocalData(GeneralConfig.localUserInfoStorageKey, user);
    this.isAuthenticated = true;
    this.currentUser = user;
  }

  /**
   * Notifies the observer that user has logged out and clears the redirectUrl.
   */
  static removeUserInfo(): void {
    LocalStorageService.removeLocalData(GeneralConfig.localUserInfoStorageKey);
    this.isAuthenticated = false;
    this.currentUser = null;
    // redirectUrl = null;
  }

  /**
   * Checks if the session data exists. Triggers isAuthenticated$ as true if exists.
   */
  static checkSessionDataExisting(): void {
    if (LocalStorageService.loadLocalData(GeneralConfig.localUserInfoStorageKey)) {
      this.isAuthenticated = true;
    }
  }
}